<template>
  <div class="course-collection">
    <div class="collection-container">
      <div class="section-header">
        <h2 class="section-title">合集列表</h2>
        <div class="section-tabs">
          <span class="tab" @click="newestRelease"  :class="{ active: activeTab === 'newest' }">最新发布</span>
          <span class="tab" @click="hottestPlays" :class="{ active: activeTab === 'hottest' }">最热播放</span>
        </div>
        <div class="section-actions">
          <span class="more-link" @click="moreClick">更多 ></span>
        </div>
      </div>

      <div class="collection-grid" v-if="!isLoading">
        <div 
          class="collection-item" 
          v-for="(course, index) in videoDatas" 
          :key="index"
        >
          <div class="course-thumbnail" :ref="setThumbnailRef" @click="goToVideo(course)">
            <div class="course-image">
              <div class="play-overlay">
                <!-- <div class="play-icon">▶</div> -->
                <keep-alive>
                  <mini-video-player  v-if="hoverStates[index]"  :data="course" @timeupdateOther="onTimeUpdate" />
                  <template v-else>
                    <miku-image class="size-full" video :res-id="course.bannerId" draggable="false" />
                  </template>
                </keep-alive>
              </div>
            </div>
            <div class="course-stats">
              <span class="views">{{ course.plays }}</span>
              <span class="likes">{{ course.danmus }}</span>
            </div>
          </div>
          <div class="course-info">
            <h3 class="course-title" @click="goToVideo(course)">{{ course.title }}</h3>
            <div class="course-meta" @click="goToUser(course.user.uri)">
              <span class="author">{{ course.user.nickname }}</span>
              <span class="date">{{ course.dynamic.publishTime.split(' ')[0] }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import videoApi from '@/apis/video';
// const pageSize = ref(12);
// const { state, execute, isLoading } = useAsyncState(()=>videoApi.getRecommend({ 
//   size: pageSize.value
// }), null, { 
//   resetOnExecute: false, 
// })
const activeTab = ref<'newest' | 'hottest'>('newest') // 当前激活的选项卡
const videoDatas = ref<any[]>([]) // 展示的数据集

const params = ref({
  pageNum: 1,
  pageSize: 6,
  type: 'VIDEO',
  keyword: '',
  sort: 'TIME'
})


// const el = useTemplateRef('elDiv')
// const hover = useElementHover(el, { delayEnter: 200, delayLeave: 200 })
// 悬浮状态管理
const thumbnailRefs = ref<HTMLElement[]>([])
const hoverStates = ref<boolean[]>([])
const setThumbnailRef = (el: HTMLElement | null) => {
  if (el) thumbnailRefs.value.push(el)
}
// console.log('video数据====',state)

// 添加时间记录
const courseTimes = ref<Record<string, number>>({})
// 修改时间更新函数
const onTimeUpdate = (time: number, value: { sid: string }) => {
  courseTimes.value[value.sid] = time
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/video/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0
  
  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}
// const url=ref('')
// const onTimeUpdate = (time: number,value:object) => {
//   console.log('time', time)
//   currentTime.value = time
//   url.value = '/video/' + value.sid
//   if (currentTime.value >= 3) {
//     url.value += '#time' + currentTime.value
//   }
//   return url
// }

onMounted(() => {
  
  hoverStates.value = new Array(thumbnailRefs.value.length).fill(false)
  
  thumbnailRefs.value.forEach((el, index) => {
    const isHovered = useElementHover(el, { 
      delayEnter: 200, 
      delayLeave: 200 
    })
    
    watch(isHovered, (value) => {
      hoverStates.value[index] = value
    })
  })
  newestRelease()
})

onBeforeUpdate(() => {
  thumbnailRefs.value = []
})

interface Course {
  title: string;
  author: string;
  date: string;
  views: string;
  likes: string;
}
// 最热播放 
const  hottestPlays = async () => { 
// if (!state.value) return
  activeTab.value = 'hottest'
//   // 直接取前6条
//   videoDatas.value = state.value.slice(0, 6)
  params.value.sort = 'PLAY'
  const datas = await videoApi.search(params.value)
  if(datas){
    videoDatas.value = datas.records
  }
}
// 最新发布  
const newestRelease = async () => { 
// if (!state.value) return
  activeTab.value = 'newest'
  // // 取最后6条（倒序排列）
  // videoDatas.value = [...state.value].reverse().slice(0, 6)
  params.value.sort = 'TIME'
  const datas = await videoApi.search(params.value)
  if(datas){
    videoDatas.value = datas.records
  }
}

// 监听state变化初始化
// watch(() => state.value, (newVal) => {
//   if (newVal) {
//     // 默认显示最新发布
//     newestRelease()
//   }
// }, { immediate: true })
//点击视频
const  goToVideo = (value: Object) => {
  const url = generateVideoUrl(value)
  window.open(url, '_blank')
}
//点击作者
const goToUser = (value: string) => {
  window.open(value, '_blank')
}

//点击更多
const moreClick = () => {
  const baseUrl = window.location.origin;
  const targetUrl = `${baseUrl}/search/video?kw=&sort=${params.value.sort}`;
  window.location.href = targetUrl;
}
const courseList = ref<Course[]>([
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  },
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  },
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  },
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  },
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  },
  {
    title: '总第5课——西大数信教学学堂（高等代数下册）',
    author: '数学系',
    date: '2024-01-15',
    views: '65',
    likes: '0'
  }
]);
</script>

<style scoped>
/* 保持原有样式不变 */
.course-collection {
  background: #fff;
  padding: 40px 0;
}

.collection-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.section-tabs {
  display: flex;
  gap: 20px;
  margin-left: 15px;
}

.tab {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #666;
}

.tab.active {
  background: #4a90e2;
  color: white;
}

.tab:hover:not(.active) {
  background: #e9ecef;
}

.section-actions {
  margin-left: auto;
}

.more-link {
  color: #4a90e2;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;
}

.more-link:hover {
  text-decoration: underline;
}

.collection-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.collection-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.collection-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.course-thumbnail {
  position: relative;
  height: 160px;
  background: #e9ecef;
}

.course-image {
  width: 100%;
  height: 100%;
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 1; /* 始终显示 */
  transition: all 0.3s ease;
  flex-shrink: 0;
  overflow: hidden;
}

.collection-item:hover .play-overlay {
  background: rgba(0, 0, 0, 0.3); /* 悬浮时添加遮罩 */
}

.play-icon {
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #333;
}

.course-stats {
  position: absolute;
  bottom: 10px;
  left: 10px;
  right: 10px;
  display: flex;
  justify-content: space-between;
  color: white;
  font-size: 12px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.course-info {
  padding: 15px;
}

.course-title {
  font-size: 14px;
  color: #333;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.author {
  color: #4a90e2;
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .section-tabs {
    width: 100%;
    justify-content: space-between;
  }

  .section-actions {
    margin-left: 0;
    width: 100%;
    text-align: right;
  }

  .collection-grid {
    grid-template-columns: 1fr;
  }
}
</style>
